# coding:utf-8

import requests
import pandas as pd

def get_sina_historical_exchange_rate(currency_pair, start_date, end_date):
    """
    获取新浪财经的历史汇率数据

    :param currency_pair: 货币对，例如 'USDCNY' 表示美元兑人民币
    :param start_date: 开始日期，格式为 'YYYY-MM-DD'
    :param end_date: 结束日期，格式为 'YYYY-MM-DD'
    :return: 包含历史汇率数据的 DataFrame
    """
    url = f"http://biz.finance.sina.com.cn/forex/forex.php?mod=history&startdate={start_date}&enddate={end_date}&symbol={currency_pair}&type=0"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
    response = requests.get(url, headers=headers)

    # 手动指定编码
    response.encoding = 'gb2312'
    
    if response.status_code == 200:
        # 使用 pandas 读取 HTML 表格
        tables = pd.read_html(response.text)
        if tables:
            df = tables[0]
            # 处理表头
            df.columns = df.iloc[0]
            df = df[1:]
            df = df.reset_index(drop=True)
            return df
        else:
            print("未找到历史汇率数据")
    else:
        print(f"请求失败，状态码: {response.status_code}")
    return None

if __name__ == '__main__':
    # 使用示例
    currency_pair = 'USDCNY'
    start_date = '2025-01-01'
    end_date = '2025-07-01'
    df = get_sina_historical_exchange_rate(currency_pair, start_date, end_date)
    if df is not None:
        print(df)